from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise

from app.core.config import settings
from app.routers import api_router
from app.middlewares.request_logger import RequestLoggerMiddleware

# 创建FastAPI应用
app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.PROJECT_VERSION,
    openapi_url=f"{settings.API_V1_STR}/openapi.json"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.BACKEND_CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    max_age=600,  # 设置预检请求结果缓存时间为600秒(10分钟)
)

# 添加请求日志中间件
app.add_middleware(RequestLoggerMiddleware)

# 注册路由
app.include_router(api_router, prefix=settings.API_V1_STR)

# 注册Tortoise-ORM
register_tortoise(
    app,
    db_url=settings.DB_URL,
    modules={"models": ["app.models.models", "app.models.log_models"]},
    generate_schemas=True,
    add_exception_handlers=True,
)

@app.get("/")
async def root():
    """根路由"""
    return {"message": "欢迎使用权限管理系统API"}



if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app="app.main:app", host="127.0.0.1", port=8081, reload=True)